package com.stars.module.setting.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stars.base.entity.CommonDTO;
import com.stars.base.exception.BaseException;
import com.stars.module.setting.entity.SystemDefine;
import com.stars.module.setting.mapper.SystemDefineMapper;
import com.stars.module.setting.service.SystemDefineService;
import com.stars.util.common.DevelopKit;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author : Rocks
 * @version : 1.0
 * @date : 2023/1/30 22:52
 * @description : 系统设置配置服务实现类
 */
@Service
public class SystemDefineServiceImpl implements SystemDefineService {

    private final SystemDefineMapper defineMapper;

    public SystemDefineServiceImpl(SystemDefineMapper defineMapper) {
        this.defineMapper = defineMapper;
    }

    @Override
    public JSONObject loadDefineList(CommonDTO dto) {

        Page<SystemDefine> page = Page.of(dto.getCurrent(), dto.getPageSize());

        LambdaQueryWrapper<SystemDefine> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(SystemDefine::getTypeText,dto.getSearch())
                .or()
                .like(SystemDefine::getConfigText,dto.getSearch());

        wrapper.orderByAsc(SystemDefine::getShowOrder);

        JSONObject result = new JSONObject();

        Page<SystemDefine> systemDefineEntityPage = defineMapper.selectPage(page, wrapper);

        result.put("list",systemDefineEntityPage.getRecords());
        result.put("total",systemDefineEntityPage.getTotal());

        return result;
    }


    @Override
    public boolean saveOrUpdate(SystemDefine entity) throws BaseException {

        LambdaQueryWrapper<SystemDefine> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .eq(SystemDefine::getSystemId,entity.getSystemId())
                .ne(SystemDefine::getId,entity.getId());

        if(defineMapper.exists(wrapper)) {
            throw new BaseException("唯一标识重复！");
        }

        if(StringUtils.hasLength(entity.getId())){
            //执行更新
            return defineMapper.updateById(entity)>0;
        }

        entity.setId(DevelopKit.generateUUID());
        DevelopKit.setBaseInfo(entity);

        return  defineMapper.insert(entity)>0;
    }

    @Override
    public int getMaxIndex() {

        Integer index = defineMapper.getMaxIndex();

        if(index == null) {
            return 0;
        }

        return index;
    }

    @Override
    public SystemDefine getDefineById(String id) {
        return defineMapper.selectById(id);
    }

    @Override
    public boolean removeDefine(String id) {
        return defineMapper.deleteDefineById(id);
    }
}
